package com.yuerlive.rainbow.module.live;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.mrd.mina.MinaHelper;
import com.pili.pldroid.player.PLNetworkManager;
import com.umeng.socialize.UMShareAPI;
import com.yuerlive.rainbow.R;
import com.yuerlive.rainbow.base.BaseActivity;
import com.yuerlive.rainbow.common.AppConfig;
import com.yuerlive.rainbow.entity.Gift;
import com.yuerlive.rainbow.entity.LiveDetailData;
import com.yuerlive.rainbow.entity.LiveInfo;
import com.yuerlive.rainbow.entity.User;
import com.yuerlive.rainbow.entity.UserInfo;
import com.yuerlive.rainbow.module.live.fragment.FragmentLiveMain;
import com.yuerlive.rainbow.module.live.fragment.FragmentPlayVideo;
import com.yuerlive.rainbow.module.live.presenter.LiveFinishContract;
import com.yuerlive.rainbow.module.live.presenter.LiveRoomContract;
import com.yuerlive.rainbow.module.live.presenter.LiveRoomPresenter;
import com.yuerlive.rainbow.observer.Observerable;
import com.yuerlive.rainbow.observer.ObserverableType;
import com.yuerlive.rainbow.utils.DownloadImage;
import com.yuerlive.rainbow.utils.L;
import com.yuerlive.rainbow.utils.LeakUtil;
import com.yuerlive.rainbow.utils.UserProxy;
import com.yuerlive.rainbow.widget.CustomDialog;

import java.lang.ref.WeakReference;
import java.net.UnknownHostException;
import java.util.List;

import butterknife.OnClick;

/**
 * Created by xiaoyi on 2017/5/19.
 */

public class LiveRoomActivity extends BaseActivity implements LiveRoomContract.View, Observerable.ISubscribe {
    private FragmentPlayVideo playvideoFragment;
    private FragmentLiveMain mainFragment;
    private static final String[] DEFAULT_PLAYBACK_DOMAIN_ARRAY = {
            "pili-live-rtmp.wangyuhudong.com"
    };

    public boolean hasDeal;
    public boolean hasFreeze;
    public boolean isBanker;
    protected CustomDialog exitDialog;
    protected CustomDialog isBankerDialog;
    LiveRoomContract.Presenter presenter;
    private boolean first = true;



    /**
     * 没有连接网络
     */
    private static final int NETWORK_NONE = -1;
    /**
     * 移动网络
     */
    private static final int NETWORK_MOBILE = 0;
    /**
     * 无线网络
     */
    private static final int NETWORK_WIFI = 1;

    private NetworkChangeReciever reciever;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_liveroom;
    }

    private Handler mH = new Handler();
    private String liveId;
    private String chatRoomID;

    @Override
    protected void initViews() {
        setTranslucentStatus(true);
        liveId = getIntent().getStringExtra("liveId");
        chatRoomID = getIntent().getStringExtra("chatroomId");
        hasFreeze = getIntent().getBooleanExtra("hasFreeze",false);
        try {
            PLNetworkManager.getInstance().startDnsCacheService(this, DEFAULT_PLAYBACK_DOMAIN_ARRAY);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        getWindow().addFlags(WindowManager.LayoutParams.
                FLAG_KEEP_SCREEN_ON);
        presenter = new LiveRoomPresenter(this);
        presenter.getLiveDetail(liveId);

        mainFragment = new FragmentLiveMain();
        Bundle data = new Bundle();
        data.putString("chatroomId", chatRoomID);
        if (getIntent().hasExtra("liveCover"))
            data.putString("liveCover", getIntent().getStringExtra("liveCover"));
        L.e(TAG, "封面" + getIntent().getStringExtra("liveCover"));
        mainFragment.setArguments(data);
        playvideoFragment = new FragmentPlayVideo();
        playvideoFragment.setArguments(data);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.fragment_content, playvideoFragment);
        transaction.add(R.id.fragment_content, mainFragment);
        transaction.show(playvideoFragment);
        transaction.show(mainFragment);
        transaction.commit();
        //initInputLayout();
//        AndroidBug5497Workaround.assistActivity(this);

        reciever = new NetworkChangeReciever(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        filter.addAction("android.net.wifi.STATE_CHANGE");
        filter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
        registerReceiver(reciever, filter);
        mH.postDelayed(() -> {
            first = true;
        }, 10000);
        Observerable.getInstance().subscribe(ObserverableType.HASDEAL, this);
        Observerable.getInstance().subscribe(ObserverableType.ISBANKER, this);
        initExitDialog();
        initIsBankerDialog();
    }


    @Override
    protected void onDestroy() {
        presenter.leaveLiveRoom(liveId);
        unregisterReceiver(reciever);

        mH.removeCallbacksAndMessages(null);
        mH = null;
        LeakUtil.fixInputMethodManagerLeak(this);
        Observerable.getInstance().unSubscribe(ObserverableType.HASDEAL, this);
        Observerable.getInstance().unSubscribe(ObserverableType.ISBANKER, this);
        exitDialog.dismiss();
        isBankerDialog.dismiss();
        super.onDestroy();
    }

    @Override
    public void setPresenter(LiveRoomContract.Presenter presenter) {
        super.presenter = presenter;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    public String getChatRoomId() {
        return chatRoomID;
    }

    @Override
    public void showLiveDetail(LiveDetailData detailData) {
        LiveInfo info = detailData.getInfo();
        info.setLiveId(liveId);
        detailData.setInfo(info);
        User user = UserProxy.getUser();
        UserInfo userInfo = user.getUserInfo();
        userInfo.setRainbowSweet(info.getRainbowSweet());
        user.setUserInfo(userInfo);
        UserProxy.setUser(user);
        playvideoFragment.setVideoPath(detailData.getInfo().getRtmp());
        mainFragment.setLiveDetail(detailData);
        if (detailData.getInfo().getState() == 0) {//
            showSnackbar(getRootView(this), "当前直播已结束，请选择其他直播间", 0);

            getRootView(this).postDelayed(() -> {
                Intent intent = new Intent(this, LiveFinishActivity.class);
                intent.putExtra("icon", detailData.getInfo().getUserIcon());
                intent.putExtra("conver", detailData.getInfo().getLiveIcon());
                jumpToActivity(intent);
                finish();
            }, 2000);
            return;
        } else if (detailData.getInfo().getState() == 1) {

        } else {
            hideVideoFragment();
        }
        List<Gift> gifts = detailData.getGiftList();
        for (Gift gift : gifts) {
            DownloadImage.getInstance().download(gift.getIcon());
        }
    }

    public void hideVideoFragment() {
        //getSupportFragmentManager().beginTransaction().remove(playvideoFragment).commit();
        playvideoFragment.showConverView();

    }

    @Override
    public <T> void update(ObserverableType key, T data) {
        switch (key) {
            case ISBANKER:
                this.isBanker = (Boolean) data;
                break;
            case HASDEAL:
                this.hasDeal = (Boolean) data;
        }

    }

    private static class NetworkChangeReciever extends BroadcastReceiver {
        WeakReference<LiveRoomActivity> weakReference;

        public NetworkChangeReciever(LiveRoomActivity liveRoomActivity) {
            this.weakReference = new WeakReference<LiveRoomActivity>(liveRoomActivity);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            int state = weakReference.get().getNetWorkState();
            if (state > -1) {
                L.e(weakReference.get().TAG, "网络连接");
                if (!weakReference.get().first)
                    MinaHelper.getInstance().connect(null, true);
            } else {
                L.e(weakReference.get().TAG, "网络连接断开");
            }
        }
    }

    public int getNetWorkState() {
        // 得到连接管理器对象
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetworkInfo = connectivityManager
                .getActiveNetworkInfo();
        if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {

            if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_WIFI)) {
                return NETWORK_WIFI;
            } else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)) {
                return NETWORK_MOBILE;
            }
        } else {
            return NETWORK_NONE;
        }
        return NETWORK_NONE;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onBackPressed() {
        if (!hasDeal && !isBanker) {
            super.onBackPressed();
        } else {
            if (isBanker) {
                isBankerDialog.show();
            } else if (hasDeal) {
                exitDialog.show();
            }
        }
    }

    private void initExitDialog() {
        if (exitDialog == null) {
            View view = View.inflate(mActivity, R.layout.layout_choose_dialog, null);
            exitDialog = new CustomDialog(mActivity, view);
            exitDialog.hide();
            view.findViewById(R.id.btnCancel).setOnClickListener((v) ->
                    exitDialog.hide()
            );
            TextView tvSure = (TextView) view.findViewById(R.id.btnSure);
            TextView tvContent = (TextView) view.findViewById(R.id.tvContent);
            tvContent.setText("离开直播间，当前下注金额会自动扣除，是否继续?");
            tvSure.setText("确定");
            tvSure.setOnClickListener((v) -> finish());
        }
    }

    private void initIsBankerDialog() {
        if (isBankerDialog == null) {
            View view = View.inflate(mActivity, R.layout.layout_choose_dialog, null);
            isBankerDialog = new CustomDialog(mActivity, view);
            isBankerDialog.hide();
            view.findViewById(R.id.btnCancel).setOnClickListener((v) ->
                    isBankerDialog.hide()
            );
            TextView tvSure = (TextView) view.findViewById(R.id.btnSure);
            TextView tvContent = (TextView) view.findViewById(R.id.tvContent);
            tvContent.setText("离开直播间，本局结算结束后，自动下庄。");
            tvSure.setText("确定");
            tvSure.setOnClickListener((v) -> finish());
        }
    }
}
